<template>
  <el-dialog
    title="登录"
    :visible.sync="login_form"
    width="300px"
    append-to-body
    :lock-scroll="false"
  >
    <div class="login">
      <div>
        <el-input
          placeholder="请输入用户名"
          v-model="username"
          clearable
          class="input_style"
        ></el-input>
      </div>
      <div>
        <el-input
          placeholder="请输入密码"
          v-model="password"
          show-password
          class="input_style"
        ></el-input>
      </div>
      <div>
        <el-button type="primary" @click="login" class="login_style"
          >登录</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>

<script>
import request from "../../request/http";
import qs from "qs";
import { mapState } from "vuex";
export default {
  name: "login",
  data() {
    return {
      username: "",
      password: "",
    };
  },
  props: ["login_form"],
  computed: {
    ...mapState({
      userid: (state) => state.user_id,
    }),
  },
  methods: {
    login() {
      if (this.username == "" || this.password == "") {
        this.$message.error("请输入账号密码");
        return;
      }
      const data = { username: this.username, password: this.password };
      request({
        url: "/login/",
        method: "post",
        data: qs.stringify(data),
      })
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("登录成功！");
            this.$store.commit("setUserId", res.data.id);
            this.$store.commit("setUserinfo", res.data);
            this.$store.commit("setName", res.data.name);
            this.$store.commit("login");
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
  },
};
</script>

<style>
.input_style {
  margin-bottom: 10px;
}
.login_style {
  width: 260px;
}
</style>
